package com.yiwei.jmx.view;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.BankSignBean;
import com.yiwei.jmx.api.bean.BankSignsmsBean;
import com.yiwei.jmx.api.bean.CheckCodeBean;
import com.yiwei.jmx.api.bean.SmsSendBean;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * Created by xsooy-pc on 18-5-22.
 */

public class PhoneIdentityDilaog extends Dialog {


    @BindView(R.id.btn_close)
    ImageView btnClose;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.progress)
    CircularProgress progress;
    private Context context;
    public String signUniqueCode;
    private String mobile;
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + "s重新获取");
//                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText("重新发送");
    }

    public PhoneIdentityDilaog(Context context) {
        this(context, R.style.DialogStyle);
    }

    public PhoneIdentityDilaog(Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
        initView();
    }

    public void setSignUniqueCode(String signUniqueCode, String mobile) {
        this.signUniqueCode = signUniqueCode;
        this.mobile = mobile;
        editPhone.setText(mobile);
    }

    private void initView() {
        setContentView(R.layout.dialog_phone_identity);
        ButterKnife.bind(this);
        setCancelable(false);

        Window mWindow = getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = Util.getDisplayMetrics(context).widthPixels;
        lp.gravity = Gravity.BOTTOM;
        if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {// 横屏
            lp.width = Util.getDisplayMetrics(context).heightPixels;
        } else {
            lp.width = Util.getDisplayMetrics(context).widthPixels;
        }
        mWindow.setAttributes(lp);

    }


    @OnTextChanged({R.id.edit_phone, R.id.edit_code})
    void onTextChange(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editPhone)) && !TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    public void getSmsSend() {
        if (!Network.checkNetwork(context)) {
            ToastUtil.show(context, "网络连接失败");
            return;
        }
        progress.setVisibility(View.VISIBLE);
        BankSignsmsBean bean = new BankSignsmsBean();
        bean.signUniqueCode = signUniqueCode;
        Api.api_service.getBankSignSms(bean).compose(RxLifeUtil.checkOn(context)).
                doFinally(() -> {
                    try {
                        progress.setVisibility(View.GONE);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(context, "发送成功，请注意查收");
                    timer.start();
                });
    }

    public void getCheckCode(String code) {
        if (!Network.checkNetwork(context)) {
            ToastUtil.show(context, "网络连接失败");
            return;
        }
        progress.setVisibility(View.VISIBLE);
        BankSignBean bean = new BankSignBean();
        bean.signUniqueCode = signUniqueCode;
        bean.code = code;
        Api.api_service.getBankSign(bean).compose(RxLifeUtil.checkOn(context)).
                doFinally(() -> {
                    try {
                        progress.setVisibility(View.GONE);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (onChooseListener != null) {
                        onChooseListener.onSuccess();
                    }
                });
    }

    @Override
    public void dismiss() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.dismiss();
    }

    private OnChooseListener onChooseListener;

    public PhoneIdentityDilaog setOnChooseListener(OnChooseListener onChooseListener) {
        this.onChooseListener = onChooseListener;
        return this;
    }

    @OnClick({R.id.btn_close, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_close:
                dismiss();
                break;
            case R.id.btn_send_code:
                if (UI.toString(editPhone).length() != 11) {
                    ToastUtil.makeText(context, "请输入正确的手机号");
                    return;
                }
                getSmsSend();
                break;
            case R.id.btn_submit:
                if (UI.toString(editPhone).length() != 11) {
                    ToastUtil.makeText(context, "请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(context, "验证码不能为空");
                    return;
                }
                getCheckCode(UI.toString(editCode));
                break;
        }
    }


    public interface OnChooseListener {
        void onSuccess();
    }
}
